window.addEventListener('DOMContentLoaded',()=>{
    //为增加按钮绑定单击事件
    document.querySelector("#addBtn").addEventListener('click',async()=>{
        //获取文本框的信息
        let tid=document.querySelector("#tid").value
        let tname=document.querySelector("#tname").value
        let age=document.querySelector("#age").value
        let lession=document.querySelector("#lession").value
        //构建成一个对象
        let teacher={tid,tname,age,lession}
        const {code,message}=await addTeacher(teacher)
        if(code){
            alert(message)
            window.location.href="index.html"
        }else{
            alert(message)
        }
    })
})

/* 增加的ajax方法 */
const addTeacher=({tid,tname,age,lession})=>{
    return new Promise((resolve,reject)=>{
        const xhr=new XMLHttpRequest()
        xhr.open("POST","/teachers/add",true)
        //设置请求头
        xhr.setRequestHeader('Content-Type',"application/x-www-form-urlencoded")
        //设置发送
        xhr.send(`tid=${tid}&tname=${tname}&age=${age}&lession=${lession}`)
        xhr.onreadystatechange=()=>{
            if(xhr.readyState==4){
                if(xhr.status==200){
                    resolve(JSON.parse(xhr.responseText))
                }
            }
        }
    })
}